package com.dmxh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dmxh.api.AddressAPI;
import com.dmxh.api.ItemAPI;
import com.dmxh.controller.OrderprePare;
import com.dmxh.dto.PayDto;
import com.dmxh.mapper.TbOrderItemMapper;
import com.dmxh.mapper.TbOrderMapper;
import com.dmxh.pojo.*;
import com.dmxh.result.Result;
import com.dmxh.service.OrderItemService;
import com.dmxh.service.OrderService;
import com.dmxh.util.IdWorker;
import com.dmxh.util.JwtUtil;
import com.dmxh.vo.AddressVo;
import com.dmxh.vo.CartVo;
import com.dmxh.vo.DetailVo;
import com.dmxh.vo.UserVO;
import io.jsonwebtoken.Claims;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.ibatis.annotations.Mapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AddressAPI addressAPI;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderItemService orderItemService;//这个

//    @Autowired
//    private TbOrderItemMapper orderItemMapper;//这个  懂了吗  启动一下 看看已经启动了  我给你演示一下

    @Autowired
    private ItemAPI itemAPI;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @GlobalTransactional//全局事务管理   作用域:可跨服务
    public PayDto crateOrder(String frontToken, OrderprePare orderprepare) {
        long addressId = Long.parseLong(orderprepare.getAddressId());
        String paymentType = orderprepare.getPaymentType();/*支付类型*/

        /*通过地址id去查询*/
        AddressVo addressVo = addressAPI.addressByIdQueryAll(addressId);

        Claims claims = JwtUtil.parseJwt(frontToken);
        String subject = claims.getSubject();
        UserVO userVO = JSON.parseObject(subject, UserVO.class);

        /*通过当前登录的用户去获取购物车  直接远程调用*/
        String userid = claims.getId();/*如果....就重新登录*/
        List<CartVo> cartList = (List<CartVo>) redisTemplate.boundHashOps("CartList").get(userid);

        List<TbOrder> orderList = new ArrayList<>();
        List<TbOrderItem> orderItemList = new ArrayList<>();
        List<TbItem> itemList = new ArrayList<>();


        long nextId = idWorker.nextId();

        BigDecimal amount = new BigDecimal(0);
        if (cartList == null) {
            throw new RuntimeException("购物车没有商品");
        }

        for (CartVo cartVo : cartList) {
            TbOrder order = new TbOrder();
            order.setOrderId(idWorker.nextId());

            order.setPaymentType(paymentType);
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(userVO.getUsername());
            order.setReceiverAreaName(addressVo.getAddress());
            order.setReceiverMobile(addressVo.getMobile());
            order.setReceiver(addressVo.getContact());
            order.setSellerId(cartVo.getSeller());
            order.setOrderNo(nextId + "");//订单编号

            /*添加到order集合里*/
            orderList.add(order);
            BigDecimal totalFee = new BigDecimal(0);
            List<DetailVo> details = cartVo.getDetails();
            for (DetailVo detail : details) {
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setId(idWorker.nextId());
                BeanUtils.copyProperties(detail, orderItem);/*相同的数据直接拷贝了*/
                orderItem.setOrderId(order.getOrderId());
                totalFee = totalFee.add(detail.getTotalFee());
                amount = amount.add(detail.getTotalFee());
                order.setPayment(orderItem.getPrice());
                orderItem.setOrderNo(order.getOrderNo());//订单编号同步

                /*扣减库存*/
                TbItem tbItem = new TbItem();
                tbItem.setId(detail.getItemId());
                tbItem.setNum(detail.getNum());
                itemList.add(tbItem);

                orderItemList.add(orderItem);
            }
        }
        itemAPI.updateItemNumById(itemList);
        int i = orderMapper.insertOrderList(orderList);
//        int i2 = 1 / 0;
        int i1 = orderItemService.insertOrderItemList(orderItemList);
        redisTemplate.boundHashOps("CartList").delete(userid);/*清空购物车*/

        /*订单超时删除订单*/
        String msg = "我是消息内容";//消息内容
        Message<String> message = MessageBuilder.withPayload(msg)
                .setHeader(MessageHeaders.CONTENT_TYPE, "text/plain")
                .build();
        rocketMQTemplate.syncSend("topicdk2310", message, 20000, 7);

        PayDto payDto = new PayDto();
        payDto.setSubject("测试商品");
        payDto.setOutTradeNo(nextId + "");
        payDto.setTotalAmount(amount);
        return payDto;
    }

    @Override
    @Transactional    /*保证两个表都能删除*/
    public boolean queryOrderStatusAndDelete() {
        /*查询order表  如果查询到数据的状态为1 就将他 关联的orderitem表中对应的数据删除  然后再将order表中的数据删除*/
        List<TbOrder> tbOrders = orderMapper.selectByExample(null);
//        List<Long> orderIds = new ArrayList<>();
        for (TbOrder tbOrder : tbOrders) {
            String status = tbOrder.getStatus();
            if (StrUtil.equals(status, "1")) {
                /*删除orderitem表中的数据*/
                orderItemService.deleteOrderItem(tbOrder.getOrderId());
//                orderIds.add(tbOrder.getOrderId());
//                orderItemMapper.deleteByExample(null);//现在换成用servic去调用了   循环依赖错误
            }
        }

//        orderItemService.deleteOrderItems(orderIds);
        /*然后根据状态 删除order表中的数据*/
        TbOrderExample orderExample = new TbOrderExample();
        orderExample.createCriteria().andStatusEqualTo("1");
        int i = orderMapper.deleteByExample(orderExample);
        return (i > 0) ? true : false;
    }

    @Override
    public boolean updateStatusByOutTradeNo(String outTradeNo) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderNo(outTradeNo);
        return (this.orderMapper.updateByPrimaryKeySelective(tbOrder) > 0) ? true : false;
    }
}
